package com.jsmile.cloud.authc.sys;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.jsmile.cloud.authc.api.req.ReqSysUserRegister;
import com.jsmile.cloud.authc.api.req.sys.ReqSysUserQuery;
import com.jsmile.cloud.authc.api.req.sys.ReqSysUserUpdate;
import com.jsmile.cloud.authc.api.res.ResSysUser;
import com.jsmile.cloud.authc.sys.model.SysRole;
import com.jsmile.cloud.authc.sys.model.SysUser;
import com.jsmile.cloud.authc.sys.repo.*;
import com.jsmile.mall.api.exception.ExceptionKit;

import cn.hutool.core.bean.BeanUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class SysUserApplicationService {

    private final SysUserSearchRepository sysUserSearchRepository;
    private final SysUserRepository sysUserRepository;
    private final SysDepartmentSearchRepository sysDepartmentSearchRepository;
    private final SysRoleSearchRepository sysRoleSearchRepository;
    private final SysRoleRepository sysRoleRepository;

    public IPage<ResSysUser> getPageList(ReqSysUserQuery reqSysUserQuery) {
        ExceptionKit.checkNotNull(reqSysUserQuery.getCurTenantId(), "租户id不能为空!");
        log.info("角色查询:{]", reqSysUserQuery);
        return sysUserSearchRepository.pageQuery(reqSysUserQuery).convert(x -> {
            ResSysUser resSysUser = BeanUtil.toBean(x, ResSysUser.class);
            List<SysRole> roles = sysRoleSearchRepository.getRoleByUserId(x.getId());
            resSysUser.setRoleId(CollectionUtils.isEmpty(roles) ? null : roles.get(0).getId());
            if (null != resSysUser.getDeptId())
                resSysUser.setDeptName(sysDepartmentSearchRepository.getById(x.getDeptId()).getDeptName());
            return resSysUser;
        });
    }

    public ResSysUser register(ReqSysUserRegister reqSysUserRegister) {
        return sysUserRepository.register(reqSysUserRegister);
    }

    public boolean saveUser(ReqSysUserUpdate reqSysUserUpdate) {
        SysUser sysUser = SysUser.create(reqSysUserUpdate);
        boolean flag = sysUserRepository.save(sysUser);
        if (null != reqSysUserUpdate.getRoleId())
            sysRoleRepository.saveUserRole(sysUser.getId(), Lists.newArrayList(reqSysUserUpdate.getRoleId()), sysUser.getTenantId());
        return flag;
    }

    public boolean updateUser(ReqSysUserUpdate reqSysUserUpdate) {
        if (null != reqSysUserUpdate.getRoleId())
            sysRoleRepository.saveUserRole(reqSysUserUpdate.getId(), Lists.newArrayList(reqSysUserUpdate.getRoleId()), reqSysUserUpdate.getTenantId());
        return sysUserRepository.updateById(SysUser.create(reqSysUserUpdate));
    }

    public boolean deleteUser(ReqSysUserUpdate reqSysUserUpdate) {
        return sysUserRepository.removeById(reqSysUserUpdate.getId());
    }
}
